import {defineStore} from "pinia";
import {ChangePassword, LoginUser, RegisterUser} from "@/entity/auth/AuthEntity";
import {changePswdService, loginService, refreshTokenService, registerService} from "@/service/auth";
import {Response} from "@/entity/net";
import {JwtToken} from "@/entity/net/Token";
import {NetSetting} from "@/setting";
import {Md5} from "ts-md5";

export const AuthStore = defineStore("authStore", {
    actions: {
        //  登录
        login(form: LoginUser): Response<JwtToken> {
            form.password = Md5.hashStr(form.password as string);
            return loginService(form);
        },
        // 注册
        register(form: RegisterUser): Response<boolean> {
            console.log(form);
            form.password = Md5.hashStr(form.password as string);
            form.rePassword = Md5.hashStr(form.rePassword as string);
            return registerService(form);
        },
        // 忘记密码
        changePassword(form: ChangePassword): Response<boolean> {
            form.rePassword = Md5.hashStr(form.rePassword as string);
            return changePswdService(form);
        },
        /**
         * token刷新服务
         */
        refreshToken(): Response<JwtToken> {
            return refreshTokenService();
        },
        isLogin() {
            return localStorage.getItem(NetSetting.accessKey) && localStorage.getItem(NetSetting.refreshKey);
        }

    }
});